const protocols = require("./api.json");
const protoPath = __dirname + "/packet/";

const Util = require("util");
const FS   = require("fs");

let header = "syntax = \"proto2\";\n\n";
let content = "message Message {\n\n    required int32 packetId = 1;\n    required float timestamp = 2;\n\n";
let index = 2;

function getAutoId() {
  index += 1;
  return index;
}

function createProtoFile(name) {
  let filePath = protoPath + name + ".proto";
  if (FS.existsSync(filePath)) { return; }
  FS.writeFileSync(filePath, "syntax = \"proto2\";\n\nmessage " + name + " {\n\n}\n");
  console.log("Create File %s.proto Finished!", name);
}

function transCode(upper) {
  let camelName = upper.replace(/^TO_|^ON_/,"").toLowerCase().replace(/_(\S)/g,(all, letter)=>{return letter.toUpperCase()});
  let className = camelName.replace(/\b(\w)|\s(\w)/g, m => {return m.toUpperCase();});

  createProtoFile(className);

  header += Util.format("import \"%s.proto\";\n", className);
  content += Util.format("    optional %s %s = %s;\n", className, camelName, getAutoId()); 
}

Object.keys(protocols).forEach(k => {
  if (k.indexOf("ON_") == 0 || k.indexOf("TO_") == 0) {
    transCode(k);
  }
});

header += "\n";
content += "\n}\n";

let message = header + content;
FS.writeFileSync(protoPath + "Message.proto", message);

console.log("Create Message.proto Finished!");
